package org.keyroy.map_editor.map.layers;

import java.util.ArrayList;
import java.util.List;

import org.keyroy.map_editor.map.Map;
import org.keyroy.map_editor.map.m.Building;
import org.keyroy.map_editor.map.m.BuildingMark;
import org.keyroy.map_editor.map.m.MapPoint;
import org.keyroy.map_editor.map.m.MapRect;
import org.keyroy.map_editor.map.m.PixPoint;
import org.keyroy.tag.Tag;
import org.keyroy.tag.XmlSupport;

public class BuildingLayer implements XmlSupport {
	public List<BuildingMark> buildings = new ArrayList<BuildingMark>();

	public void add(Map map, Building building) {
		buildings.add(new BuildingMark(building.ID, new MapPoint(building.mapRect)));
	}

	public void add(Map map, Building building, List<MapRect> mapRects) {
		for (int i = 0; i < mapRects.size(); i++) {
			MapRect mapRect = mapRects.get(i);
			int col = mapRect.width / building.mapRect.width;
			int row = mapRect.height / building.mapRect.height;

			for (int x = 0; x < col; x++) {
				for (int y = 0; y < row; y++) {
					MapPoint mapPoint = new MapPoint(mapRect);
					mapPoint.move(x * building.mapRect.width, y * building.mapRect.height);
					buildings.add(new BuildingMark(building.ID, mapPoint));
				}
			}
		}
	}

	public BuildingMark get(Map map, PixPoint pixPoint) {
		for (int i = 0; i < buildings.size(); i++) {
			BuildingMark bm = buildings.get(i);
			Building building = map.resource.loadBuliding(bm.sID, map);
			building.setLocation(map, bm.mapPoint);

			if (building.pixRect.isIntersectingRect(pixPoint)) {
				return bm;
			}
		}
		return null;
	}

	public final void removeBuilding(Map map, MapRect rect) {
		try {
			rect.reset();
			for (int i = 0; i < buildings.size(); i++) {
				BuildingMark bm = buildings.get(i);
				Building building = map.resource.loadBuliding(bm.sID, map);
				building.setLocation(map, bm.mapPoint);

				if (rect.isIntersectingRect(building.mapRect)) {
					buildings.remove(i);
					i--;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public final void setBuilding(MapPoint mapPoint, BuildingMark building) {
		building.mapPoint.setLocation(mapPoint);
		buildings.remove(building);
		buildings.add(building);
	}

	public final void deleteBuilding(BuildingMark buildingMark) {
		try {
			buildings.remove(buildingMark);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void removeBuilding(int id) {
		for (int i = 0; i < buildings.size(); i++) {
			BuildingMark bm = buildings.get(i);
			if (bm.sID == id) {
				buildings.remove(i);
				i--;
			}
		}
	}

	@Override
	public String getTagName() {
		return "bl";
	}

	@Override
	public void initObj(Tag tag) {
		tag.getChildObjectArray(BuildingMark.class, buildings);
	}

	@Override
	public void initTag(Tag tag) {
		tag.addChild(buildings);
	}

}
